package com.erp.itm.service.impl;

import com.erp.itm.dao.ProjectUsersDao;
import com.erp.itm.domain.ProjectUsersDO;
import com.erp.oa.domain.NotifyRecordDO;
import com.erp.system.domain.UserDO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.erp.itm.dao.ProjectDao;
import com.erp.itm.domain.ProjectDO;
import com.erp.itm.service.ProjectService;

@Service
public class ProjectServiceImpl implements ProjectService {
	@Autowired
	private ProjectDao projectDao;
	@Autowired
	private ProjectUsersDao projectUsersDao;
	
	@Override
	public ProjectDO get(Long id){
		return projectDao.get(id);
	}
	
	@Override
	public List<ProjectDO> list(Map<String, Object> map){
		return projectDao.list(map);
	}
	
	@Override
	public int count(Map<String, Object> map){
		return projectDao.count(map);
	}
	
	@Override
	public int save(ProjectDO project){
		int r  = projectDao.save(project);
		saveProjectUser(project);
		return r;
	}
	
	@Override
	public int update(ProjectDO project){
		int r = projectDao.update(project);
		if(project.getUserIds() != null && project.getUserIds().length>0){
			//删除原有的项目组，重新添加
			int m = projectUsersDao.deleteByItmid(project.getId());
			saveProjectUser(project);
		}
		return r;
	}

	/**
	 * 保存项目组成员
	 * @param project
	 */
	private void saveProjectUser(ProjectDO project) {
		Long[] userIds = project.getUserIds();
		if(userIds == null){
			userIds[0]=project.getUserIdCreate();
		}
		Long itmid = project.getId();
		List<ProjectUsersDO> projectUsersDO = new ArrayList<>();
		for (Long userId : userIds) {
			ProjectUsersDO projectUsers = new ProjectUsersDO();
			projectUsers.setProjectId(itmid);
			projectUsers.setUserId(userId);
			projectUsersDO.add(projectUsers);
		}
		projectUsersDao.batchSave(projectUsersDO);
	}

	@Override
	public int remove(Long id){
		return projectDao.remove(id);
	}
	
	@Override
	public int batchRemove(Long[] ids){
		return projectDao.batchRemove(ids);
	}

	@Override
	public List<ProjectDO> getNotEndProjectlist() {
		return projectDao.getNotEndProjectlist();
	}

	@Override
	public int updatereceivedAmount(BigDecimal receiptAmount, Long projectId) {
		return projectDao.updatereceivedAmount(receiptAmount,projectId);
	}

	@Override
	public int updateinvoiceAmount(BigDecimal invoiceAmount, Long projectId) {
		return projectDao.updateinvoiceAmount(invoiceAmount,projectId);
	}

	@Override
	public List<String> getCustName() {
		return projectDao.getCustName();
	}

	@Override
	public List<ProjectDO> getProjectlistByStatus(Long id) {
		return projectDao.getProjectlistByStatus(id);
	}

}
